package com.easyban.controller;

import java.io.*;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import com.easyban.Dto.SessionWebUserDto;
import com.easyban.Dto.UserSpaceDto;
import com.easyban.annotation.GlobalInterceptor;
import com.easyban.annotation.VerifyParam;
import com.easyban.config.EmaileCode;
import com.easyban.config.WebConfig;
import com.easyban.constants.Constants;
import com.easyban.entity.dao.CreateImageCode;
import com.easyban.entity.enums.ResponseCodeEnum;
import com.easyban.entity.enums.VerifyRegexEnum;
import com.easyban.entity.po.UserInfo;
import com.easyban.entity.query.UserInfoQuery;
import com.easyban.entity.vo.ResponseVO;
import com.easyban.exception.BusinessException;
import com.easyban.service.UserInfoService;
import com.easyban.utils.RedisUtils;
import com.easyban.utils.ScaleFilter;
import com.easyban.utils.StringTools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * 用户信息 Controller
 */
@RestController
public class UserInfoController extends ABaseController{
	private final Logger log=LoggerFactory.getLogger(UserInfoController.class);
	private static final String CONTENT_TYPE = "Content-Type";
	private static final String CONTENT_TYPE_VALUE = "application/json;charset=UTF-8";

    @Resource
    private RedisUtils redisUtils;
	@Resource
	private UserInfoService userInfoService;
	@Resource
	private EmaileCode emaileCode;
	@Resource
	private WebConfig webConfig;
	@RequestMapping("/checkCode")
	public void checkcode(HttpServletResponse response, HttpSession session, Integer type) throws IOException {
		CreateImageCode imageCode = new CreateImageCode(130, 38, 5, 10);
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		String code = imageCode.getCode();
		System.out.println("验证码"+code);
		System.out.println(type);
		if (type==0 || code==null){
			session.setAttribute(Constants.CHECK_CODE_KEY,code);
		}
		else {
			session.setAttribute(Constants.CHECK_CODE_KEY_EMAIL,code);
		}
		// log.info("CHECK_CODE_KEY_EMAIL : "+(String)session.getAttribute(Constants.CHECK_CODE_KEY_EMAIL));
		imageCode.write(response.getOutputStream());
	}
	@RequestMapping("/sendEmailCode")
	public ResponseVO sendEmailCode(HttpSession session, @VerifyParam(required = true) String email,
									@VerifyParam(required = true) String checkCode,
									@VerifyParam(required = true) Integer type){
		try {
			if (StringTools.isEmpty(email)|| StringTools.isEmpty(checkCode) || type==null){
				throw  new BusinessException(ResponseCodeEnum.CODE_601);
			}
            String code = (String) session.getAttribute(Constants.CHECK_CODE_KEY_EMAIL);
			if (!checkCode.equalsIgnoreCase(code)){
				throw  new BusinessException("图片验证码不正确");
			}
			String randomNumber = StringTools.getRandomNumber(5);
			redisUtils.cacheValue(Constants.CHECK_CODE_KEY_EMAIL_TWO+email,randomNumber,Constants.READIS_TIME);
			emaileCode.sendEmailCode(email,randomNumber);
			return getSuccessResponseVO("发送成功");
		}
		finally {
			session.removeAttribute(Constants.CHECK_CODE_KEY_EMAIL);
		}
	}
	@RequestMapping("/register")
	public ResponseVO register(HttpSession session,
							   @VerifyParam(required = true, regex = VerifyRegexEnum.EMAIL, max = 150) String email,
							   @VerifyParam(required = true, max = 20) String nickName,
							   @VerifyParam(required = true, regex = VerifyRegexEnum.PASSWORD, min = 8, max = 18) String password,
							   @VerifyParam(required = true) String checkCode,
							   @VerifyParam(required = true) String emailCode) {
		try{
			String  value = (String )session.getAttribute(Constants.CHECK_CODE_KEY);
			if (!checkCode.equalsIgnoreCase(value)) {
				throw new BusinessException("图片验证码不正确");
			}
			userInfoService.register(email, nickName, password, emailCode);
			return getSuccessResponseVO(null);
		}
		finally {
			session.removeAttribute(Constants.CHECK_CODE_KEY);
		}
	}
	@RequestMapping("/login")
	public ResponseVO login(   HttpSession session,
							   @VerifyParam(required = true, regex = VerifyRegexEnum.EMAIL, max = 150) String email,
							   @VerifyParam(required = true, regex = VerifyRegexEnum.PASSWORD, min = 8, max = 18) String password,
							   @VerifyParam(required = true) String checkCode) {
			String  value = (String )session.getAttribute(Constants.CHECK_CODE_KEY);
			if (!checkCode.equalsIgnoreCase(value)) {
				throw new BusinessException("图片验证码不正确");
			}
		SessionWebUserDto login = userInfoService.login(email, password);
		return getSuccessResponseVO(login);
	}
	@RequestMapping("/logout")
	public ResponseVO logout(HttpSession session) {
	session.removeAttribute(Constants.SESSION_KEY);
	return getSuccessResponseVO(null);
	}
	@RequestMapping("/qqlogin")
	public ResponseVO qqlogin(HttpSession session) {
		session.removeAttribute(Constants.SESSION_KEY);
		return getSuccessResponseVO(null);
	}
	@RequestMapping("/resetPwd")
	public ResponseVO resetPwd(HttpSession session,
							   String email,
							   @VerifyParam(required = true, regex = VerifyRegexEnum.PASSWORD, min = 8, max = 18) String password,
							   @VerifyParam(required = true) String checkCode,
							   @VerifyParam(required = true) String emailCode) {
		try {
			String  value = (String )session.getAttribute(Constants.CHECK_CODE_KEY);
			if (!checkCode.equalsIgnoreCase(value)) {
				throw new BusinessException("图片验证码不正确");
			}
			userInfoService.resetPwd(email, password, emailCode);
			return getSuccessResponseVO(null);
		} finally {
			session.removeAttribute(Constants.CHECK_CODE_KEY);
		}
	}
	@RequestMapping("/settings/{useimage}")
	@GlobalInterceptor(checkLogin = true, checkParams = true)
	public void getAvatarUs(HttpServletResponse response, @VerifyParam(required = true) @PathVariable("useimage") String useimage) {
		String avatarFolderName = Constants.FILE_FOLDER_FILE + Constants.FILE_FOLDER_AVATAR_NAME;
		String avatarPath = webConfig.getProjectFolder() + avatarFolderName+useimage;
		File file = new File(avatarPath);
		String imageFolder = Constants.FILE_FOLDER_AVATAR_NAME;
		String imageName =useimage;
		if (!file.exists()) {
			imageName = Constants.AVATAR_DEFUALT;
			if (!new File(webConfig.getProjectFolder() + avatarFolderName + Constants.AVATAR_DEFUALT).exists()) {
				printNoDefaultImage(response);
				return;
			}
		}
		readImage(response, imageFolder, imageName);
	}
	@GetMapping("/getAvatar/{useimage}")
	@GlobalInterceptor(checkLogin = false, checkParams = false)
	public void getAvatar(HttpServletResponse response, @VerifyParam(required = true) @PathVariable("useimage") String useimage) {
		String avatarFolderName = Constants.FILE_FOLDER_FILE + Constants.FILE_FOLDER_AVATAR_NAME;
		String avatarPath = webConfig.getProjectFolder() + avatarFolderName+useimage+Constants.AVATAR_SUFFIX;
		File file = new File(avatarPath);
		String imageFolder = Constants.FILE_FOLDER_AVATAR_NAME;
		String imageName =useimage+Constants.AVATAR_SUFFIX;
		if (!file.exists()) {
			imageName = Constants.AVATAR_DEFUALT;
			if (!new File(webConfig.getProjectFolder() + avatarFolderName + Constants.AVATAR_DEFUALT).exists()) {
				printNoDefaultImage(response);
				return;
			}
		}
		readImage(response, imageFolder, imageName);
	}


	private void printNoDefaultImage(HttpServletResponse response) {
		response.setHeader(CONTENT_TYPE, CONTENT_TYPE_VALUE);
		response.setStatus(HttpStatus.OK.value());
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.print("请在头像目录下放置默认头像default_avatar.jpg");
			writer.close();
		} catch (Exception e) {
			log.error("输出无默认图失败", e);
		} finally {
			writer.close();
		}
	}
	private void readImage(HttpServletResponse response, String imageFolder, String imageName) {
		ServletOutputStream sos = null;
		FileInputStream in = null;
		ByteArrayOutputStream baos = null;
		try {
			if (StringTools.isEmpty(imageFolder) || StringUtils.isBlank(imageName)) {
				return;
			}
			String imageSuffix = StringTools.getFileSuffix(imageName);
			String filePath = webConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + Constants.FILE_FOLDER_IMAGE + imageFolder + "/" + imageName;
			if (Constants.FILE_FOLDER_TEMP_2.equals(imageFolder)) {
				filePath = webConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + imageFolder + "/" + imageName;
			} else if (imageFolder.contains(Constants.FILE_FOLDER_AVATAR_NAME)) {
				filePath = webConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + imageFolder + imageName;
			}
			File file = new File(filePath);
			if (!file.exists()) {
				return;
			}
			imageSuffix = imageSuffix.replace(".", "");
			if (!Constants.FILE_FOLDER_AVATAR_NAME.equals(imageFolder)) {
				response.setHeader("Cache-Control", "max-age=2592000");
			}
			response.setContentType("image/" + imageSuffix);
			in = new FileInputStream(file);
			sos = response.getOutputStream();
			baos = new ByteArrayOutputStream();
			int ch = 0;
			while (-1 != (ch = in.read())) {
				baos.write(ch);
			}
			sos.write(baos.toByteArray());
		} catch (Exception e) {
			log.error("读取图片异常", e);
		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (sos != null) {
				try {
					sos.close();
				} catch (IOException e) {
					log.error("IO异常", e);
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					log.error("IO异常", e);
				}
			}
		}
	}
 @RequestMapping("/updateUserAvatar")
	@GlobalInterceptor(checkLogin = true)
	public ResponseVO uploadImage(MultipartFile avatar,HttpSession session) {

	 SessionWebUserDto sessionAttribute =(SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
	 String filee=webConfig.getProjectFolder()+Constants.FILE_FOLDER_FILE+Constants.FILE_FOLDER_AVATAR_NAME;
	 File file1 = new File(filee);
	 if (!file1.exists()){
		 file1.mkdirs();
	 }
	 File targeFile=new File(filee+"/"+sessionAttribute.getUserId()+Constants.AVATAR_SUFFIX);
	 try {
		 avatar.transferTo(targeFile);
	 }
	 catch (Exception e){
		 log.info("上串文件失败");
		 throw new BusinessException("上传文件失败");
	 }
	 UserInfo userInfo = new UserInfo();
	 userInfo.setQqAvatar(sessionAttribute.getUserId()+Constants.AVATAR_SUFFIX);
	 userInfoService.updateUserInfoByUserId(userInfo, sessionAttribute.getUserId());
	 /*更新一下session*/
	 sessionAttribute.setAvatar(sessionAttribute.getUserId()+Constants.AVATAR_SUFFIX);
	 session.setAttribute(Constants.SESSION_KEY,sessionAttribute);
	 return getSuccessResponseVO(null);
 }



}